package com.zhm.demo.hive.dev.cfg;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.zhm.demo.hive.dev.mapper"}, sqlSessionFactoryRef = "sqlSessionFactoryHiveDev")
public class HiveDevCfg {

    @Bean(name = "dataSourceHiveDev")
    public DataSource dataSourceHiveDev() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("org.apache.hive.jdbc.HiveDriver");//如果不配置druid会根据url自动识别dbType，然后选择相应的driverClassName
        dataSource.setUrl("jdbc:hive2://hadoop002:10000/ods");
        dataSource.setUsername("hadoop");
//        dataSource.setPassword("123456");
        dataSource.setValidationQuery("select 1");//用来检测连接是否有效
        dataSource.setTestOnBorrow(false);//借用连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能
        dataSource.setTestOnReturn(false);//归还连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能
        //连接空闲时检测，如果连接空闲时间大于timeBetweenEvictionRunsMillis指定的毫秒，执行validationQuery指定的SQL来检测连接是否有效
        dataSource.setTestWhileIdle(true);//如果检测失败，则连接将被从池中去除
        dataSource.setTimeBetweenEvictionRunsMillis(60000);//1分钟
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(5);
        return dataSource;

    }

    // 自定义逻辑删除的全局配置
    public GlobalConfig globalConfig() {
        GlobalConfig gc = new GlobalConfig();
        gc.getDbConfig();
        return gc;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryHiveDev() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceHiveDev());
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:com/zhm/demo/hive/dev/mapper/xml/*.xml")
        );
        //向Mybatis过滤器链中添加拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        factoryBean.setPlugins(interceptor);
        factoryBean.setGlobalConfig(globalConfig());
        factoryBean.setTypeAliasesPackage("com.zhm.demo.hive.entity");
        return factoryBean.getObject();
    }


}
